package com.apes.fn.server.praticalFunction.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.server.praticalFunction.model.AdapterClassify;
import com.apes.fn.server.praticalFunction.model.CommodityExpandConfig;
import com.apes.fn.server.praticalFunction.model.SmartAccessoriesConfig;
import com.apes.fn.server.praticalFunction.repository.AdapterClassifyRepository;
import com.apes.fn.server.praticalFunction.repository.SmartAccessoriesConfigRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.cache.Cache;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.pi.service.PiManager;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.repository.CategoryDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.swing.*;
import java.util.*;
import java.util.stream.Collectors;


/**
 * Created by lishikun on 2021/6/11 15:04
 */
@Service("smartAccessoriesConfigService")
public class SmartAccessoriesConfigService extends DomainService {
    @Autowired
    private SmartAccessoriesConfigRepository smartAccessoriesConfigRepository;
    @Autowired
    private Cache cache;
    @Autowired
    private AdapterClassifyRepository adapterClassifyRepository;
    @Autowired
    private PiManager piManager;
    @Autowired
    private CategoryDao categoryDao;
    private final String CONST_DEFAULT_CACHENAME = "smartAccessoriesConfigCache";
    private final String CONST_CONFIG_KEY = "config";

    public SmartAccessoriesConfig save(SimpleRequest request) {
        SmartAccessoriesConfig smartAccessoriesConfig = request.getO(SmartAccessoriesConfig.class);
        for (CommodityExpandConfig commodityExpandConfig : smartAccessoriesConfig.getCommodityExpandConfigs()) {
            if (commodityExpandConfig.getFilterCondition() != null && !"{}".equals(commodityExpandConfig.getFilterCondition().toString())) {
                commodityExpandConfig.setFilterConditions(commodityExpandConfig.getFilterCondition() != null ? commodityExpandConfig.getFilterCondition().toString() : null);
            }
            if ("{}".equals(commodityExpandConfig.getFilterCondition().toString())) {
                commodityExpandConfig.setFilterCondition(null);
            }
        }
        checkData(smartAccessoriesConfig);
        SmartAccessoriesConfig config = smartAccessoriesConfigRepository.saveAndFlush(smartAccessoriesConfig);
        cache.remove(CONST_DEFAULT_CACHENAME);
        this.setCacheOfSmartAccessoriesConfig(new SimpleRequest());
        return smartAccessoriesConfigRepository.findOne(config.getId());
    }

    public String delete(SimpleRequest request) {
        SmartAccessoriesConfig smartAccessoriesConfig = request.getO(SmartAccessoriesConfig.class);
        smartAccessoriesConfigRepository.delete(smartAccessoriesConfig);
        cache.remove(CONST_DEFAULT_CACHENAME);
        this.setCacheOfSmartAccessoriesConfig(new SimpleRequest());
        return "删除成功";
    }

    // 设置智选配件配置缓存
    public Object setCacheOfSmartAccessoriesConfig(SimpleRequest request) {
        String CACHE_INIT_FLAG = "initFlag";
        List<AdapterClassify> adapterCategories = adapterClassifyRepository.findAll();
        Map cacheSmartAccessoriesConfig = new HashMap();
        List<Map> classifyTree = (List<Map>)invoke("cm.classify.findTreeData", "");
        for (AdapterClassify adapterClassify : adapterCategories) {
            if (adapterClassify.getSmartAccessoriesConfig().isValid()) {
                List<Map> classifyLastStage = getClassifyLastStage(adapterClassify.getClassify().getId(), classifyTree, adapterClassify.getSmartAccessoriesConfig());
                for (Map map : classifyLastStage) {
                    cacheSmartAccessoriesConfig.put(map.get("id"), map);
                }
            }
        }
        cache.put(CONST_DEFAULT_CACHENAME, CONST_CONFIG_KEY,cacheSmartAccessoriesConfig);
        cache.put(CONST_DEFAULT_CACHENAME, CACHE_INIT_FLAG, true);
        return cache.get(CONST_DEFAULT_CACHENAME, CONST_CONFIG_KEY);
    }

    public void checkData(SmartAccessoriesConfig smartAccessoriesConfig) {
        if (!smartAccessoriesConfig.isValid())return;
        List<Map> classifyTree = (List<Map>)invoke("cm.classify.findTreeData", "");
        List<AdapterClassify> adapterCategories = adapterClassifyRepository.findAll();
        // 去除配件配置
        if (smartAccessoriesConfig.getId() != null) {
            adapterCategories = adapterClassifyRepository.findAllBySmartAccessoriesConfig(smartAccessoriesConfig.getId());
        }
        List<Map> tableClassifyLastStage = new ArrayList();
        List<Map> newClassifyLastStage;
        // 获取数据库的配置的末级数据

        for (AdapterClassify adapterCategory : adapterCategories) {
            tableClassifyLastStage.addAll(getClassifyLastStage(adapterCategory.getClassify().getId(), classifyTree, adapterCategory.getSmartAccessoriesConfig()));
        }
        for (AdapterClassify adapterClassify : smartAccessoriesConfig.getAdapterCategories()) {
            // 获取前端传过来的配置的末级数据
            newClassifyLastStage = getClassifyLastStage(adapterClassify.getClassify().getId(), classifyTree, adapterClassify.getSmartAccessoriesConfig());
            // 末级数据是否存在
            for (Map newClassifyLastStageMap : newClassifyLastStage) {
                Object id = newClassifyLastStageMap.get("id");
                List<Map> mapList = tableClassifyLastStage.stream().filter(map -> {
                    if (map.get("id").equals(id)) return true;
                    else return false;
                }).collect(Collectors.toList());
                if (mapList.size() != 0 )
                    throw new RuntimeException("当前方案品类编码:" +(smartAccessoriesConfig.getId())+
                            ",与生效的方案产生冲突,方案号:"  + (((HashMap)mapList.get(0).get("smartAccessoriesConfig")).get("id")) +
                            "品类编码：" + (mapList.get(0).get("classifyId")));

            }
        }
    }
    // 根据商品品类编码，获取商品品类末级数据
    private List getClassifyLastStage(String classifyId, List<Map> classifyTree, SmartAccessoriesConfig smartAccessoriesConfig) {
//        Map mapped = MapUtil.mapped(smartAccessoriesConfig);
        Map mapped = MapUtil.mapper("id", smartAccessoriesConfig.getId(),
        "matchingProductConfig", smartAccessoriesConfig.getMatchingProductConfig(),
        "smartAccessoriesConfig", smartAccessoriesConfig.getSmartAccessoriesConfig());
        return classifyTree.parallelStream().filter(map -> {
            if (map.get("path").toString().indexOf(classifyId) > 0 && (Boolean) map.get("lastStage") == true)
                return true;
            else return false;
        }).map(map -> {
            map.put("smartAccessoriesConfig", mapped);
            map.put("classifyId", classifyId);
            map.put("displayFilter", smartAccessoriesConfig.isFilterCondition());
            return map;
        }).collect(Collectors.toList());
    }
    // 筛选条件分发器
    public Object getFilterConditions(SimpleRequest request) {
        JSONObject jo = request.getJO();
        JSONObject group = jo.getJSONObject("group");
        JSONArray filters = group.getJSONArray("filters");
        jo.put("size", 40);
        Pageable pageable = PageRequest.of((Integer.valueOf(1)), request.get("size"));
        if("FC0001".equals(filters.getJSONObject(0).getString("value"))) {
            return invoke("cm.product.getProductComment", jo);
        } else {
            String value = filters.getJSONObject(1).getString("value");
            if (value == null) throw new RuntimeException("扩展属性末级品类不允许为空");
            JSONArray jsonArray = piManager.synErp("KzbService.queryKZBMX", MapUtil.mapper("PLIDS", value,"tableName", "KZB")).getJSONArray("obj");
            return MapUtil.mapper("total", jsonArray.size(), "page", 1, "size", jsonArray.size(), "elements", jsonArray.size(),
                    "page", 0,"content", jsonArray);
        }
    }

    public Object getFilter(SimpleRequest request) {
        SmartAccessoriesConfig smartAccessoriesConfig = smartAccessoriesConfigRepository.findOne(request.getJO().getJSONObject("filterCondition").
                getJSONObject("smartAccessoriesConfig").getString("id"));
        String classifyId = request.getJO().getJSONObject("filterCondition").getString("classifyId");
        List filter = new ArrayList();
        String PZCXID = request.getJO().getString("PZCXID");
        String PJMCID = request.getJO().getString("id");
//        String PJMCID = "000609";
//        String PZCXID = "AGO0118A00880";

        for (CommodityExpandConfig commodityExpandConfig : smartAccessoriesConfig.getCommodityExpandConfigs()) {
            // 属于基础属性
            JSONObject jsonObject;
            if("FC0001".equals(commodityExpandConfig.getFilterSource().getId())) {
                jsonObject = new JSONObject();
                jsonObject.put("COLUMN_NAME", commodityExpandConfig.getFilterCondition().getString("COLUMN_NAME"));
                if(commodityExpandConfig.getFilterShowName() != null)
                    jsonObject.put("filterShowName", commodityExpandConfig.getFilterShowName());
                jsonObject.put("CLASSIFY_ID", classifyId);
                jsonObject.put("PJMCID", PJMCID);
                jsonObject.put("PZCXID", PZCXID);
                jsonObject.put("tableName", "SPXX");
                filter.add(
                        MapUtil.mapper("key", commodityExpandConfig.getFilterCondition().getString("COLUMN_NAME"),
                                "name", commodityExpandConfig.getFilterCondition().getString("COMMENTS"),
                                "type", commodityExpandConfig.getFilterSource().getId(),
                                "values", piManager.synErp("ipmQuerySpxxService.getSPXX",jsonObject).getJSONArray("obj")));
            } else {
            // 属于扩展属性
                jsonObject = new JSONObject();
                jsonObject.put("COLUMN_NAME", commodityExpandConfig.getFilterCondition().getString("COLUMN_NAME"));
                jsonObject.put("tableName", "KZB");
                jsonObject.put("KZBID", commodityExpandConfig.getFilterCondition().getString("KZBID"));
                jsonObject.put("PJMCID", PJMCID);
                jsonObject.put("PZCXID", PZCXID);
                filter.add(
                        MapUtil.mapper("key", commodityExpandConfig.getFilterCondition().getString("COLUMN_NAME"),
                                "name", commodityExpandConfig.getFilterCondition().getString("COMMENTS"),
                                "type", commodityExpandConfig.getFilterSource().getId(),
                                "values", piManager.synErp("ipmQuerySpxxService.getSPXX",jsonObject).getJSONArray("obj")));
            }
        }
        return filter;
    }
}
